﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication10
{
    //
    //坐标的结构体用来存储坐标的颜色，行列，竖列，分数；
    //
    public struct ChessPoint     
    {
        public int ChessRow;
        public int ChessCol;
        public int ChessType;
        public int Sorce;
    };

    public partial class Five_in_a_row : Form
    {
        //***********局域网对战**************************
        public static int[,] arr = new int[16, 16];      //用二维数组记录棋盘中的黑白棋和空位置；
        int[,] ChessInWindowX = new int[16, 16];         //记录棋子在窗口中的横坐标；
        int[,] ChessInWindowY = new int[16, 16];         //记录棋子在窗口中的纵坐标；
        int Chess_type = 1;                             //1表示黑色棋子，2表示白色棋子；
        int GameOver= 0;                                //游戏的输赢，1表示赢，0表示输；
        public MessClass SendChessMeg;                  //用于局域网发送的棋子信息；
        public MessClass ReceiveChessMeg;               //局域网接受的棋子信息；
        public bool ConnectState;                       //连接状态，连接成功后才可以下棋；
        public UdpClient Udpserver;                     //服务器，用于接受对方传来的数据；
        public UdpClient Udpclient;                     //客户端，用来发送数据；
        public Thread thr;                              //线程，用于服务器监听；
        //**********************************************
                 

        //***************设置窗口阴影效果******************
        private const int CS_DropSHADOW = 0x20000;
        private const int GCL_STYLE = (-26);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SetClassLong(IntPtr hwnd, int nIndex, int dwNewLong);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int GetClassLong(IntPtr hwnd, int nIndex);
        //**************************************************


        //*****************人机对战*************************
        public bool[,,,] AnWinCombin=new bool [2,15,15,572];  //获胜组合；
        public int[,]AnWinCombiCount =new int [2,572];        //获胜组合编号中棋子的个数；
        public int[] AnCombindex = new int[20];
        public int[] AnCombiCount = new int[20];
        public int[] AnRule = new int[5];
        public int NTempCount;                             //临时记录索引值；
        public int nCount=0;                               //获胜组合编号; 
        public bool GamewithPC=true;                       //是否选择人机对战；
        public int Step_Munber=0;                          //走的步数；
        public bool StartGame=false;
        //**************************************************

        //
        //构造函数
        //
        public Five_in_a_row()
        {
            InitializeComponent();
            toolStripContainer1.Visible = false;
            ReceiveChessMeg = new MessClass();
            Txt_IPAddress.Text = "172.19.237.183";

            //
            //设置窗口阴影；
            //
            SetClassLong(this.Handle, GCL_STYLE, GetClassLong(this.Handle, GCL_STYLE) | CS_DropSHADOW);
            
           
            //设置还没连接时棋盘不能下棋；
            ConnectState = false;
          
            //
            //设置音效
            //
            //System.Media.SoundPlayer player = new System.Media.SoundPlayer();
            //player.SoundLocation = Application.StartupPath+"//1.wav";

            //
            //获取本机的IP地址;
            //没有插入网线的时候需要把下面两行消掉/
            //
           //IPAddress[] ips= Dns.GetHostAddresses(Dns.GetHostName());
           //You_IPAddress.Text = ips[2].ToString();

            //**************人机对战*****************
            InitWinCombi();  //初始化获胜组合
            
           
        }

        //对类进行实例化声明；
        [Serializable]
        //
        //棋子的类结构，成员变量有在窗口的横纵坐标，二维数组中的横纵坐标，棋子的类型，是否胜利，用于局域网的数据通信
        //
        public class MessClass
        {
            public int CImageInWindowX = 0;
            public int CImageInWindowY = 0;
            public int In_arrY = 0;
            public int In_arrX = 0;
            public bool Chesstype = true;
            public bool Grow = true;
            public bool Victory;
        }

        //
        //监听函数
        //
        private void StartLinstener()
        { 
            
            IPEndPoint ipreceive = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                string strs;
                byte[] receives = Udpserver.Receive(ref ipreceive);
                strs = Encoding.UTF8.GetString(receives);
                char[] separator = { '-', '-', '-', '-', '-' ,'-'};
                string[] str1 = strs.Split(separator);
                ReceiveChessMeg.CImageInWindowX = int.Parse(str1[0]);
                ReceiveChessMeg.CImageInWindowY = Convert.ToInt32(str1[1]);
                ReceiveChessMeg.In_arrX = int.Parse(str1[2]);
                ReceiveChessMeg.In_arrY = int.Parse(str1[3]);
                ReceiveChessMeg.Chesstype = Convert.ToBoolean(str1[4]);
                ReceiveChessMeg.Grow = Convert.ToBoolean(str1[5]);
                ReceiveChessMeg.Victory = Convert.ToBoolean(str1[6]);

                Graphics g = DrawWindow.CreateGraphics();
                Image image;
                if (!ReceiveChessMeg.Chesstype)
                {
                    arr[ReceiveChessMeg.In_arrY, ReceiveChessMeg.In_arrX] = 1;
                    image = Properties.Resources.黑棋子;
                }
                else
                {
                    arr[ReceiveChessMeg.In_arrY, ReceiveChessMeg.In_arrX] = 2;
                    image = Properties.Resources.白棋子;
                }

                ChessInWindowX[ReceiveChessMeg.In_arrY, ReceiveChessMeg.In_arrX] = ReceiveChessMeg.CImageInWindowX;
                ChessInWindowY[ReceiveChessMeg.In_arrY, ReceiveChessMeg.In_arrX] = ReceiveChessMeg.CImageInWindowY;
                g.DrawImage(image, ReceiveChessMeg.CImageInWindowX, ReceiveChessMeg.CImageInWindowY, 37, 37);

                if (ReceiveChessMeg.Victory)
                {
                    SendChessMeg.Victory = false;
                    if (!ReceiveChessMeg.Chesstype)
                    {
                        ConnectState = false;
                        if (MessageBox.Show("恭喜黑色棋子取得胜利!", "游戏结束！！", MessageBoxButtons.OK) == DialogResult.OK)
                        {
                            ConnectState = true;
                        }
                    }

                    else
                    {
                        ConnectState = false;
                        if (MessageBox.Show("恭喜白色棋子取得胜利！", "游戏结束！！", MessageBoxButtons.OK) == DialogResult.OK)
                        {
                            ConnectState = true;
                        }
                    }
                   
                    Rebegaingame();
                }     
            } 
        }

        //
        //判断输赢查找函数
        //
        public void Arithmetic(int n, int Arow, int Acolumn)
        {
            bool Lbol = true;
            bool Rbol = true;
            int count = 1;
           
            //横向查找;
            for (int i = 1; i < 5; i++)
            {
                if (Acolumn - i < 1)
                    Rbol = false;
                if (Acolumn + i > 15)
                    Lbol = false;

                if(Rbol)
                {
                    if (arr[Arow, Acolumn - i] == n)
                        count++;
                    else
                        Rbol = false;
                }

                if(Lbol)
                {
                    if (arr[Arow, Acolumn + i] == n)
                        count++;
                    else
                        Lbol = false;
                
                }

                if (count >= 5)
                {
                    GameOver = 1;
                    return;
                }
                else
                    GameOver = 0;

            }

            //纵向查找；
            Lbol = true;
            Rbol = true;
            count = 1;
            int j;
            for (j = 1; j < 5; j++)
            {

                if (Arow - j <= 0)
                    Lbol = false;
                if (Arow + j >= 16)
                    Rbol = false;

                if (Lbol)
                {
                    if (arr[Arow - j, Acolumn] == n)                    
                        ++count;                           
                    else
                        Lbol = false;
                }

                if (Rbol)
                {
                    if (arr[Arow + j, Acolumn] == n)
                        ++count;
                    else
                        Rbol = false;
                }
                if (count >= 5)
                {
                    GameOver = 1;
                    return;
                }
                else
                    GameOver = 0;

            }
            //  正斜查找；

            Lbol = true;
            Rbol = true;
            count = 1;

            for(int i=1;i<5;i++)
            {
                if (Arow - i < 1 || Acolumn - i < 1)
                    Rbol = false;
                if (Arow + i > 15 || Acolumn + i > 15)
                    Lbol = false;

                if(Rbol)
                {
                    if (arr[Arow - i, Acolumn - i] == n)
                        count++;
                    else
                        Rbol = false;
                }
                if(Lbol)
                {
                    if (arr[Arow + i, Acolumn + i] == n)
                        count++;
                    else
                        Lbol = false;                
                }

                if (count >= 5)
                {
                    GameOver = 1;
                    return;
                }
                else
                    GameOver = 0;

            }

            //反斜查找；

            Rbol = true;
            Lbol = true;
            count = 1;
            for(int i=1;i<5;i++)
            {
                if (Arow - i < 1 || Acolumn + i > 15)
                    Rbol = false;
                if (Arow + i > 15 || Acolumn - i < 1)
                    Lbol = false;

                if(Rbol)
                {
                    if (arr[Arow - i, Acolumn + i] == n)
                        count++;
                    else
                        Rbol = false;
                }

                if(Lbol)
                {
                    if (arr[Arow + i, Acolumn - i] == n)
                        count++;
                    else
                        Lbol = false;
                
                }
                if (count >= 5)
                {
                    GameOver = 1;
                    return;
                }
                else
                    GameOver = 0;
            
            }
        }

        //
        //游戏胜利重绘界面
        //
        private void Rebegaingame()                            
        {
            for(int i=1;i<=15;i++)
            {
                for(int k=1;k<=15;k++)
                {
                    arr[i, k] = 0;
                } 
            }
            Graphics e = DrawWindow.CreateGraphics();
            e.DrawImage(Properties.Resources.局域网五子棋, 0, 0, DrawWindow.Width, DrawWindow.Height);       
        }

        //
        //最主要的函数，实现鼠标点击窗口绘制棋子和接受数据后绘制棋子
        //人机大战中，电脑分析棋局后绘制棋子
        //
        private void panel1_MouseClick_1(object sender, MouseEventArgs e)
        {
            if (StartGame)
            {
                if (GamewithPC)                          //人机对战
                {
                    ChessPoint spPoint;
                    Graphics g = DrawWindow.CreateGraphics();
                    Image image;
                    //玩家下棋；
                    image = Properties.Resources.黑棋子;
                    int x = Convert.ToInt32(Math.Round(e.X + 37.0) / 37) - 8;
                    int y = Convert.ToInt32(Math.Round(e.Y + 37.0) / 37) - 1;
                    if (x < 16 && y < 16 && x > 0 && y > 0)
                    {
                        if (arr[y - 1, x - 1] != 2 && arr[y - 1, x - 1] != 1)
                        {
                            //*****音效*****
                            //System.Media.SoundPlayer player = new System.Media.SoundPlayer();
                            //player.SoundLocation = "D://1.wav";
                            //player.Play();

                            g.DrawImage(image, (x + 7) * 37 - 15, y * 37 - 18, 37, 37);
                            Step_Munber++;
                            arr[y - 1, x - 1] = 1;
                            Arithmetic(1, y - 1, x - 1);
                            if (GameOver == 1)
                            {
                                MessageBox.Show("恭喜玩家(黑棋子)获胜！");
                                Rebegaingame();
                                InitWinCombi();
                                Step_Munber = 0;
                            }
                            ModWinCombin(y - 1, x - 1, 1);

                            //电脑下棋；
                            if (Step_Munber < 2)      //电脑天元点；
                            {
                                spPoint = GetFristPoint();
                            }
                            else
                            {
                                spPoint = GetBestPoint();
                            }
                            ModWinCombin(spPoint.ChessRow, spPoint.ChessCol, 0);
                            image = Properties.Resources.白棋子;
                            g.DrawImage(image, (spPoint.ChessCol + 8) * 37 - 15, (spPoint.ChessRow + 1) * 37 - 18, 37, 37);
                            Step_Munber++;
                            arr[spPoint.ChessRow, spPoint.ChessCol] = 2;
                            Arithmetic(2, spPoint.ChessRow, spPoint.ChessCol);
                            if (GameOver == 1)
                            {
                                MessageBox.Show("恭喜玩家(白棋子)获胜！");
                                Rebegaingame();
                                InitWinCombi();
                                Step_Munber = 0;
                            }
                        }
                    }

                }
                else                                          //局域网对战
                {
                    if (ConnectState == true)
                    {
                        ////音效
                        //System.Media.SoundPlayer player = new System.Media.SoundPlayer();
                        //player.SoundLocation = "D://1.wav";
                        //player.Play();

                        SendChessMeg = new MessClass();
                        if (ReceiveChessMeg.Grow)
                        {
                            Graphics g = DrawWindow.CreateGraphics();
                            Image image;
                            int x = Convert.ToInt32(Math.Round(e.X + 37.0) / 37) - 8;
                            int y = Convert.ToInt32(Math.Round(e.Y + 37.0) / 37) - 1;
                            if (x < 16 && y < 16 && x > 0 && y > 0)
                            {
                                if (arr[y, x] != 2 && arr[y, x] != 1)
                                {
                                    if (ReceiveChessMeg.Chesstype)
                                    {
                                        image = Properties.Resources.黑棋子;
                                        Chess_type = 1;
                                        arr[y, x] = 1;
                                    }
                                    else
                                    {
                                        image = Properties.Resources.白棋子;
                                        Chess_type = 2;
                                        arr[y, x] = 2;
                                    }
                                    ChessInWindowX[y, x] = e.X;
                                    ChessInWindowY[y, x] = e.Y;

                                    g.DrawImage(image, (x + 7) * 37 - 15, y * 37 - 18, 37, 37);
                                    Arithmetic(Chess_type, y, x);

                                    if (GameOver == 1)
                                        SendChessMeg.Victory = true;
                                    else
                                        SendChessMeg.Victory = false;

                                    //将棋子的信息传送到远程主机；

                                    SendChessMeg.CImageInWindowX = (x + 7) * 37 - 15;
                                    SendChessMeg.CImageInWindowY = y * 37 - 18;
                                    SendChessMeg.In_arrX = x;
                                    SendChessMeg.In_arrY = y;
                                    SendChessMeg.Chesstype = !ReceiveChessMeg.Chesstype;
                                    SendChessMeg.Grow = ReceiveChessMeg.Grow;
                                    ReceiveChessMeg.Grow = false;
                                    string strs = SendChessMeg.CImageInWindowX.ToString() + "-" + SendChessMeg.CImageInWindowY.ToString() + "-" + SendChessMeg.In_arrX.ToString() + "-" + SendChessMeg.In_arrY.ToString() + "-" + SendChessMeg.Chesstype.ToString() + "-" + SendChessMeg.Grow.ToString() + "-" + SendChessMeg.Victory.ToString();
                                    byte[] datass = Encoding.UTF8.GetBytes(strs);
                                    Udpclient = new UdpClient();
                                    IPEndPoint ipsend = new IPEndPoint(IPAddress.Parse(Txt_IPAddress.Text), int.Parse(TB_ReceivePort.Text));
                                    Udpclient.Send(datass, datass.Length, ipsend);
                                    Udpclient.Close();

                                    //查看游戏是否胜利
                                    if (GameOver == 1)
                                    {
                                        if (Chess_type == 1)
                                        {
                                            ConnectState = false;
                                            if (MessageBox.Show("恭喜黑色棋子取得胜利!", "游戏结束！！", MessageBoxButtons.OK) == DialogResult.OK)
                                            {
                                                ConnectState = true;
                                            }
                                        }
                                        else
                                        {
                                            ConnectState = false;
                                            if (MessageBox.Show("恭喜白色棋子取得胜利！", "游戏结束！！", MessageBoxButtons.OK) == DialogResult.OK)
                                            {
                                                ConnectState = true;
                                            }
                                        }

                                        Rebegaingame();
                                    }
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show("对方还没下好，请稍等！");
                        }
                    }
                }
            }

        }

        
        //画布重绘函数，二维数组记录了棋子在窗口中的坐标，可以实现重绘
        
        private void panel1_Paint_1(object sender, PaintEventArgs e)
        {
            Image image = Properties.Resources.局域网五子棋;
            e.Graphics.DrawImage(Properties.Resources.局域网五子棋, 0, 0, DrawWindow.Width, DrawWindow.Height);

            for (int i = 1; i <= 15; i++)
            {
                for (int k = 1; k <= 15; k++)
                {
                    if (arr[i, k] == 1)
                    {
                        image = Properties.Resources.黑棋子;
                        e.Graphics.DrawImage(image, ChessInWindowX[i, k], ChessInWindowY[i, k], 48, 48);
                    }
                    if (arr[i, k] == 2)
                    {
                        image = Properties.Resources.白棋子;
                        e.Graphics.DrawImage(image, ChessInWindowX[i, k], ChessInWindowY[i, k], 48, 48);
                    }
                }
            }
        }   

        //窗口关闭函数
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (Bt_Start_Link.Enabled == false)
            {
                thr.Abort();
                Udpserver.Close();
            }
        }


        
        //序列化和反序列化类；
        public class ClassSerializers
        {
            public ClassSerializers()
            {
                //
                // TODO: 在此处添加构造函数逻辑
                //
            }

            #region Binary Serializers
            public System.IO.MemoryStream SerializeBinary(object request)
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                System.IO.MemoryStream memStream = new System.IO.MemoryStream();
                serializer.Serialize(memStream, request);
                return memStream;
            }

            public object DeSerializeBinary(System.IO.MemoryStream memStream)
            {
                memStream.Position = 0;
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                object newobj = deserializer.Deserialize(memStream);
                memStream.Close();
                return newobj;
            }
            #endregion
        }

        //
        //开始连接按钮，用于连接远程的主机还有检查各个TextBox是否有输入数据
        //
        private void button1_Click_1(object sender, EventArgs e)
        {
            if (Txt_IPAddress.Text == "" && TB_ReceivePort.Text == "" && TB_ListenPort.Text== "")
            {

                ConnectState = true;
                int a = Convert.ToInt32(TB_ListenPort.Text);
                Udpserver = new UdpClient(a);
                thr = new Thread(new ThreadStart(StartLinstener));
                thr.Start();
                Bt_Start_Link.Enabled = false;
            }
            else
            {
                MessageBox.Show("请输入对方的IP地址和对应的端口号！", "提示");
            }
        }
        private void label4_MouseEnter(object sender, EventArgs e)
        {
            Font f = new Font("汉仪方叠体繁", 25);
            Exit_Game.Font = f;
        }

        private void label4_MouseLeave(object sender, EventArgs e)
        {
            Font f = new Font("汉仪方叠体繁", 18);
            Exit_Game.Font = f;
        }

        private void label4_Click(object sender, EventArgs e)
        {
            if (Bt_Start_Link.Enabled==false)
            {
                thr.Abort();
                Udpserver.Close();
            }

            this.Close();
        }

        private void label5_Click(object sender, EventArgs e)
        {
            if (toolStripContainer1.Visible == true)
                toolStripContainer1.Visible = false;
            else
                toolStripContainer1.Visible = true;
        }



        ///**************************************************************
        //                人机对战的相关函数
        //             数字1代表黑子，数字0代表白子
        //              玩家黑棋子，电脑白棋子
        //**************************************************************

        //初始化获胜组合；
        private void InitWinCombi()
        {
            //初始化获胜组合；
            for (int i = 0; i < 15; i++)
            {
                for (int j = 0; j < 15; j++)
                {
                    for (int k = 0; k < 572; k++)
                    {
                        AnWinCombin[0, i, j, k] = false;
                        AnWinCombin[1, i, j, k] = false;
                    }
                }
            }
            //设置各个获胜组合中填入的棋子数为0；
            for(int i=0;i<572;i++)
            {
                AnWinCombiCount[0,i]=0;
                AnWinCombiCount[1,i]=0;
            }
            nCount = 0;
            //设置垂直方向的获胜组合
            for (int i = 0; i < 15; i++)
            {
                for (int j = 0; j < 11; j++)
                {
                    for (int k = 0; k < 5; k++)
                    {
                        AnWinCombin[0, j + k, i, nCount] = true;
                        AnWinCombin[1, j + k, i, nCount] = true;
                    }
                    nCount++;
                }
            }
            
            //设置纵横方向的获胜组合
            for (int i = 0; i < 15; i++)
            {
                for (int j = 0; j < 11; j++)
                {
                    for (int k = 0; k < 5; k++)
                    {
                        AnWinCombin[0, i, j + k, nCount] = true;
                        AnWinCombin[1, i, j + k, nCount] = true;
                    }
                    nCount++;
                }

            }
            
            //设置"\"方向的获胜组合
            for (int i = 0; i < 11; i++)
            {
                for (int j = 0; j < 11; j++)
                {
                    for (int k = 0; k < 5; k++)
                    {
                        AnWinCombin[0, j + k, i + k, nCount] = true;
                        AnWinCombin[1, j + k, i + k, nCount] = true;
                    }
                    nCount++;
                }
            }
            //设置"/"方向的获胜组合
            for (int i = 0; i < 11; i++)
            {
                for (int j = 14; j >=4; j--)
                {
                    for (int k = 0; k < 5; k++)
                    {
                        AnWinCombin[0, j - k, i + k, nCount] = true;
                        AnWinCombin[1, j - k, i + k, nCount] = true;
                    }
                    nCount++;
                }
            }

        }

        //更新获胜组合；
      private  void ModWinCombin(int nRow,int nCol,int Chess_Type)//Chess_Type=0为白色棋子，1为黑色棋子
        {
             int nPlayer=0;    //棋子的类型：0为白子棋；
            
             for (int i = 0; i < 572; i++)
             {
                 //本方下子，增加获胜组合；
                 nPlayer = 0;
                 if (Chess_Type == 1)  //如果棋子的类型是黑子棋；
                     nPlayer = 1;      //变为黑子棋；
                 if (AnWinCombin[nPlayer, nRow, nCol, i] && AnWinCombiCount[nPlayer, i] != -1)//并且这个获胜组合还有机会赢
                 {
                     AnWinCombiCount[nPlayer, i]++;  //这个获胜组合中的棋子数+1；
                 }

                 //对方下子，减少获胜组合
                 nPlayer = 1;
                 if (Chess_Type == 1)  //如果棋子的类型是白色棋子
                     nPlayer = 0;
                 if (AnWinCombin[nPlayer, nRow, nCol, i])
                 {
                     AnWinCombin[nPlayer, nRow, nCol, i] = false;
                     AnWinCombiCount[nPlayer, i] = -1;  //此获胜组合不可能再取胜；
                 }
             }
        }

        //棋局评估
        private void SetRule(int nOwn)
        {
            if(nOwn==0)
            {
                AnRule[0] = 0;
                AnRule[1] = 5;
                AnRule[2] = 50;
                AnRule[3] = 510;
                AnRule[4] = 10000;
            }
            else
            {
                AnRule[0] = 0;
                AnRule[1] = 5;
                AnRule[2] = 50;
                AnRule[3] = 500;
                AnRule[4] = 5000;
            }
        }

        //空棋位打分
       private int GiveSorce(int nRow,int nCol,int Chess_Type)//Chess_Type=0为白子棋，1为黑子棋；
        {
            int nScore = 0;
            int nPlayer = 1;
            int nCount = 0;
            if (Chess_Type == 0)
                nPlayer = 0;
            for (int i = 0; i < 572; i++)
            {
                if (AnWinCombin[nPlayer, nRow, nCol, i])
                {
                    nCount = AnWinCombiCount[nPlayer, i];
                    if (nCount > 0)
                        nScore += AnRule[nCount];
                }
            }
            return nScore;
        }

        //
       //分析棋局找到分数最大的落子点
       //
        private int  GetMaxScorePoint(ref  ChessPoint point,int Chess_Type)         
       {
           int[,] anSorceMatrix = new int[15, 15];
           int nMaxSorce = 0;
           int nSorce;

            //得到空棋位分数
           for (int i = 0; i < 15; i++)
           {
               for (int j = 0; j < 15; j++)
               {
                   int Chess_status = arr[i, j];
                   if (Chess_status == 1)     //如果此位置是黑棋；
                       anSorceMatrix[i, j] = -1;
                   else if (Chess_status == 2)    //如果此位置是白棋；
                       anSorceMatrix[i, j] = 1;
                   else
                   {
                       //给空棋位打分
                       nSorce = GiveSorce(i, j, Chess_Type);
                       anSorceMatrix[i, j] = nSorce;
                       if (nSorce > nMaxSorce)
                       {
                           nMaxSorce = nSorce;
                           point.Sorce = nMaxSorce;
                           point.ChessRow = i;
                           point.ChessCol = j;
                       }
                   }
               }
           }
           /*if (Chess_Type == 0)
           {

               label7.Text = "";
               for (int i = 0; i < 15; i++)
               {
                   for (int j = 0; j < 15; j++)
                   {
                       if (anSorceMatrix[i, j] < 10 && anSorceMatrix[i, j] >= 0)
                           label7.Text += "0" + anSorceMatrix[i, j] + " ";
                       else
                           label7.Text += anSorceMatrix[i, j] + " ";
                   }
                   label7.Text += '\n';
               }
               label7.Text += "电脑最高分：" + nMaxSorce.ToString();
           }
           else
           {
               label8.Text = "";
               for (int i = 0; i < 15; i++)
               {
                   for (int j = 0; j < 15; j++)
                   {
                       if (anSorceMatrix[i, j] < 10 && anSorceMatrix[i, j] >= 0)
                           label8.Text += "0" + anSorceMatrix[i, j] + " ";
                       else
                           label8.Text += anSorceMatrix[i, j] + " ";
                   }
                   label8.Text += '\n';
               }
               label8.Text += "玩家最高分：" + nMaxSorce.ToString();
           }*/

            return nMaxSorce;
        }

        private void Put(ChessPoint point)                              //假设下到这一点，再分析对手的棋局
        {
            int nPlayer = 1;
            arr[point.ChessRow, point.ChessCol] = 1;

            if (point.ChessType == 0)
            {
                nPlayer = 0;
                arr[point.ChessRow, point.ChessCol] = 2;
            }
            NTempCount = 0;
            
            for(int i=0;i<572;i++)
            {
               //暂时更改玩家信息
                if(AnWinCombin[nPlayer,point.ChessRow,point.ChessCol,i]&&AnWinCombiCount[nPlayer,i]!=-1)
                {
                    AnCombindex[NTempCount] = i;
                    AnWinCombin[nPlayer, point.ChessRow, point.ChessCol, i] = false;

                    AnCombiCount[NTempCount] = AnWinCombiCount[nPlayer, i];
                    AnWinCombiCount[nPlayer, i] = -1;
                    NTempCount++;
                }
            }  
        }

        private void Clear(ChessPoint point)                                  //清除假设下棋的棋子
        {
            int nPlayer = 1;
            if (point.ChessType == 0)
                nPlayer = 0;

            arr[point.ChessRow, point.ChessCol] = 0;
            for(int i=0;i<NTempCount;i++)
            {
                AnWinCombin[nPlayer, point.ChessRow, point.ChessCol, AnCombindex[i]] = true;
                AnWinCombiCount[nPlayer, AnCombindex[i]] = AnCombiCount[i];
            }
        }                             
        //
        //开局下第一点，天元点。天元点被下，则下到[8,8]那点
        //
        private ChessPoint GetFristPoint()                                  
        {
            ChessPoint c;
           if(arr[7,7]!=1)
           {
               c.ChessRow = 7;
               c.ChessCol = 7;
           }
           else
           {
               c.ChessRow = 8;
               c.ChessCol = 8;
           }
           c.ChessType = -1;
           c.Sorce = -1;
           return c;
        }

        //
        //对比电脑玩家和对手的最高分，来确定最佳落子点，采用攻还是防守
        //
        private ChessPoint GetBestPoint()                                  
        {
            ChessPoint spOwnBestPoint;
            ChessPoint spPeerBestPoint;
            ChessPoint spBestPoint;
            int nOwnMaxSorce;
            int nPeerMaxSorce;

            spOwnBestPoint.Sorce = spOwnBestPoint.ChessType = spOwnBestPoint.ChessRow = spOwnBestPoint.ChessCol = -1;
            spPeerBestPoint.Sorce = spPeerBestPoint.ChessType = spPeerBestPoint.ChessRow = spPeerBestPoint.ChessCol = -1;
            spOwnBestPoint.ChessType = 0; //电脑为白色棋子；
            spPeerBestPoint.ChessType = 1;//电脑为黑色棋子；

            //设置评分规则
            SetRule(0);  //设置白色即电脑的评分规则；
            nOwnMaxSorce = GetMaxScorePoint(ref spOwnBestPoint, 0);
            Put(spOwnBestPoint);

            SetRule(1);
            nPeerMaxSorce = GetMaxScorePoint(ref spPeerBestPoint, 1);
            Clear(spOwnBestPoint);

            spBestPoint = spOwnBestPoint;
            if (nPeerMaxSorce > nOwnMaxSorce)
                spBestPoint = spPeerBestPoint;

            return spBestPoint;
        }                                

        private void bt_PTP_Click(object sender, EventArgs e)                //局域网五子棋开始游戏按钮点击事件
        {
            GamewithPC = false;
            toolStripContainer3.Visible = false;
            bt_GameWithPC.Enabled = false;
            StartGame = true;
        }           

        private void bt_GameWithPC_Click(object sender, EventArgs e)       //人机对战五子棋开始游戏按钮点击事件
        {
            GamewithPC = true;
            toolStripContainer3.Visible = false;
            bt_PTP.Enabled = false;
            StartGame = true;
        }       

        private void bt_PTP_MouseEnter(object sender, EventArgs e)           //进入 局域网五子棋开始游戏按钮 时放大按钮
        {
            bt_PTP.Width = 200;
            bt_PTP.Height = 100;
            //音效
            //System.Media.SoundPlayer player = new System.Media.SoundPlayer();
            //player.SoundLocation = "D://1.wav";
            //player.Play();
        }                 

        private void bt_PTP_MouseLeave(object sender, EventArgs e)         //离开 局域网五子棋开始游戏按钮 时缩小按钮
        {
            bt_PTP.Width = 180;
            bt_PTP.Height = 80;
        }

        private void bt_GameWithPC_MouseEnter(object sender, EventArgs e)      //进入 人机对战五子棋开始游戏按钮 时放大按钮
        {
            bt_GameWithPC.Width = 200;
            bt_GameWithPC.Height = 100;
            //音效
            //System.Media.SoundPlayer player = new System.Media.SoundPlayer();
            //player.SoundLocation = "D://1.wav";
            //player.Play();
        }

        private void bt_GameWithPC_MouseLeave(object sender, EventArgs e)       //离开 人机对战五子棋开始游戏按钮 时缩小按钮
        {
            bt_GameWithPC.Width = 180;
            bt_GameWithPC.Height = 80;
        }

        private void ReturnMenu_Click(object sender, EventArgs e)
        {
            GamewithPC = true;
            toolStripContainer3.Visible = true;
            bt_GameWithPC.Enabled = true;
            bt_PTP.Enabled = true;
            StartGame =false;
        } 
        
    }
}

